//@flow

/**
 * 请求分析器
 * 
 * 列出所有请求，最多20条
 * 包含字段：响应状态、查看详细请求、查看响应详细
 * 如果有新的响应回来了，会有效果提示
 * 内部维护数据变化
 * 支持复制操作
 */
import React, { Component } from 'react';
import { 
    FlatList,
    View,
    Text,
    StyleSheet,
    ViewStyle,
    DeviceEventEmitter,
    EmitterSubscription,
 } from 'react-native';
import * as Noti from "./requestAnalyzer.contant";
import { RequestAnalyzerItem } from './requestAnalyzerItem';
export type ReqStatus = 'success'|'fail'|'process'//请求状态：成功、失败、处理中
export type ReqMethod = 'get'|'post'|'put'|'delete'
export type DataProps = {
    id     : string,//请求ID
    status : ReqStatus,//请求状态
    reqUrl : string,//请求地址
    params : Object,//请求的参数
    header : Object,//请求头
    method : ReqMethod,//请求方法
    response:Response,//响应
}

type Props = {
    style : ViewStyle,
}
type State = {
    data  : Array<DataProps>
}
let ReqList : Array<DataProps> = [];
export class RequestAnalyzer extends Component <Props,State>{
    /**初始化state */
    state: State = {
        data : ReqList,
    }
    /**编辑内部属性 */
    _dataSourceListener :EmitterSubscription ;//数据源监听
    _dataStatusListener :EmitterSubscription ;//请求状态监听
    static data : Array<DataProps>;
    /**监听数据源变化 */
    addListender(){
        this._dataSourceListener=DeviceEventEmitter.addListener(Noti.UPDATE_ADD_REQUEST_SOURCE_NOTI,(data)=>{
            let reqModal : DataProps = data;
            this.addData(reqModal);
        })
        this._dataStatusListener = DeviceEventEmitter.addListener(Noti.UPDATE_RESPONSE_BACK_NOTI,(data)=>{
            let res : DataProps = data;
        })
    }
    /**移除监听 */
    removeListener(){
        this._dataSourceListener.remove()
    }
    /**修改数据源：添加数据 */
    addData(data:DataProps){
        let list : Array<DataProps> = this.state.data;
        list.splice(0,0,data)
        this.updateData(list);
    }
    /**更新数据源 */
    updateData(data:Array<DataProps>){
        this.setState({
            data:data
        },()=>{
            ReqList = this.state.data;
        })
    }
    /**修改状态 */
    updateStatus(data:DataProps){
        let list : Array<DataProps> = this.state.data;
        list = list.map(item=>{
            if(item.id == data.id){
                return data;
            }
            return item
        })
        this.updateData(list)
    }
    /**生命周期 */
    componentDidMount(){
        this.addListender()
    }
    componentWillUnmount(){
        this.removeListener()
    }
    render(){
        return (
            <View>
                <Text>{JSON.stringify(ReqList)}</Text>
                <FlatList 
                    data={this.state.data}
                    keyExtractor={(item,index)=>item.id}
                    renderItem={({item})=>{
                        return <RequestAnalyzerItem data={item} key={item.id}/>
                    }}/>
            </View>
        )
    }
}